package com.lmh.backend.controller;

import com.lmh.backend.entity.Author;
import com.lmh.backend.entity.News;
import com.lmh.backend.entity.User;
import com.lmh.backend.service.AuthorService;
import com.lmh.backend.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Set;

@Controller
@RequestMapping(value = "/author")
public class AuthorController {
    private AuthorService authorService;
    private NewsService newsService;
    @Autowired
    public void setAuthorService(AuthorService authorService) {
        this.authorService = authorService;
    }
    @Autowired
    public void setNewsService(NewsService newsService) {
        this.newsService = newsService;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String authorRegister(HttpServletRequest request, HttpServletResponse response,
                                 RedirectAttributes attributes) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String password = request.getParameter("password");
        String valid = request.getParameter("valid");
        // 不一致则返回注册界面并提示错误信息
        if(!password.equals(valid)) {
            attributes.addAttribute("passwordError", "两次密码输入不一致");
            return "redirect:/user/register";
        }
        String authorName = request.getParameter("username");
        // 有重复用户名则返回注册界面并提示错误信息
        Author existAuthor = authorService.getAuthorByName(authorName);
        // 无重复用户名则将用户数据存入数据库
        if(existAuthor != null) {
            attributes.addAttribute("usernameError", "用户已存在");
            return "redirect:/user/register";
        }
        Author newAuthor = new Author();
        newAuthor.setUsername(authorName);
        newAuthor.setPassword(password);
        authorService.save(newAuthor);
        // 注册成功后将username存入cookie
        Cookie cookie = new Cookie("username", authorName);
        cookie.setMaxAge(60 * 60 * 24);
        cookie.setPath("/");
        response.addCookie(cookie);
        // session存储
        request.getSession().setAttribute("role", "AUTHOR");
        return "redirect:home";
    }

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public String authorLogin(HttpServletRequest request, HttpServletResponse response,
                              RedirectAttributes attributes) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 查找有无此用户
        String authorName = request.getParameter("username");
        String password = request.getParameter("password");
        Author realAuthor = authorService.getAuthorByName(authorName);
        // 没有则返回登录界面并提示错误信息
        if(realAuthor == null) {
            attributes.addAttribute("notMatchError", "用户名不存在");
            return "redirect:/user/hello";
        }
        // 有则检验密码是否匹配
        if(!realAuthor.getPassword().equals(password)) {
            attributes.addAttribute("notMatchError", "用户名或密码错误");
            return "redirect:/user/hello";
        }
        // 然后将用户名存入cookie
        Cookie cookie = new Cookie("username", authorName);
        cookie.setMaxAge(60 * 60 * 24);
        cookie.setPath("/");
        response.addCookie(cookie);
        // session存储
        request.getSession().setAttribute("role", "AUTHOR");
        // 最后重定向到主页
        return "redirect:home";
    }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView authorHome(@CookieValue(value = "username", required = false)String username) {
        Author author = authorService.getAuthorByName(username);
        ModelAndView mv = new ModelAndView("authorHome");
        mv.addObject("author", author);
        return mv;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView editPage() {
        ModelAndView mv = new ModelAndView("editPage");

        return mv;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String authorEdit(@CookieValue(value = "username", required = false)String authorName,
                             HttpServletRequest request) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        newsService.addNews(title, content, authorName);
        return "redirect:home";
    }

    @RequestMapping(value = "/manage_news", method = RequestMethod.GET)
    public ModelAndView manageNewsPage(@CookieValue(value = "username", required = false)String authorName) {
        ModelAndView mv = new ModelAndView("manageNews");
        Author author = authorService.getAuthorByName(authorName);
        Set<News> newsSet = author.getNewsSet();
        mv.addObject("newsSet", newsSet);
        return mv;
    }

    @RequestMapping(value = "/check_edit/{newsId}", method = RequestMethod.GET)
    public ModelAndView checkEditPage(@PathVariable Long newsId){
        News news = newsService.getNewsById(newsId);
        ModelAndView mv = new ModelAndView("checkEditPage");
        mv.addObject("news", news);
        return mv;
    }

    @RequestMapping(value = "/check_edit/{newsId}", method = RequestMethod.POST)
    public String handleCheck(@PathVariable Long newsId, HttpServletRequest request){
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        News news = newsService.getNewsById(newsId);
        String new_title = request.getParameter("title");
        String new_content = request.getParameter("content");
        if(!new_title.equals(news.getTitle()) || !new_content.equals(news.getContent())){
            newsService.editNews(news.getId(), new_title, new_content);
        }
        return "redirect:/author/manage_news";
    }

    @RequestMapping(value = "/del_news/{newsId}", method = RequestMethod.GET)
    public String handleDel(@PathVariable Long newsId){
        newsService.delNews(newsId);
        return "redirect:/author/manage_news";
    }

    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String exit(HttpServletResponse response) {
        // 删除cookie
        Cookie cookie = new Cookie("username", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:/user/hello";
    }
}
